from app import db
from app.models.met import Mets


class WorkoutRecord(db.Model):
    __tablename__ = 'workout_record'

    workout_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.String(255), db.ForeignKey('user_info.user_id'), nullable=False)  # 外键，关联用户表
    age = db.Column(db.Integer)
    gender = db.Column(db.Integer)
    weight = db.Column(db.Float)
    height = db.Column(db.Float)
    max_BPM = db.Column(db.Integer)
    avg_BPM = db.Column(db.Integer)
    resting_BPM = db.Column(db.Integer)
    duration_hours = db.Column(db.Float)
    calories_burn = db.Column(db.Float)
    workout_type = db.Column(db.String(50))
    body_fat = db.Column(db.Float)
    water_intake_L = db.Column(db.Float)
    workout_frequency = db.Column(db.Integer)
    experience_level = db.Column(db.String(20))
    BMI = db.Column(db.Float)
    dream_weight = db.Column(db.Float)
    exercise = db.Column(db.Text)
    weather_conditions = db.Column(db.String(50))
    exercise_intensity = db.Column(db.String(50)) # 对应met intensity
    waist = db.Column(db.Float)
    hip = db.Column(db.Float)
    waist_hip_ratio = db.Column(db.Float)
    thigh = db.Column(db.Float)
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
    updated_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())
    recipe_id = db.Column(db.Integer, db.ForeignKey('recipes.recipe_id'), nullable=True)  # 关联 `recipes` 表

    # 关联 Met 表
    # met_id = db.Column(db.Integer, db.ForeignKey('met.met_id'), nullable=True)
    # met = db.relationship('Met', backref='workout_records', lazy=True)
    # 关联用户信息表
    user = db.relationship('UserInfo', backref='workout_records')
    recipe = db.relationship('Recipe', backref='workout_records')  # 关联的食谱

    def __repr__(self):
        return f"<WorkoutRecord {self.workout_id}, user_id={self.user_id}, workout_type={self.workout_type}>"

    def to_dict(self):
        return {
            "id": self.workout_id,
            "user_id": self.user_id,
            "age": self.age,
            "gender": self.gender,
            "weight": self.weight,
            "height": self.height,
            "max_BPM": self.max_BPM,
            "avg_BPM": self.avg_BPM,
            "resting_BPM": self.resting_BPM,
            "duration_hours": self.duration_hours,
            "calories_burn": self.calories_burn,
            "workout_type": self.workout_type,
            "body_fat": self.body_fat,
            "water_intake_L": self.water_intake_L,
            "workout_frequency": self.workout_frequency,
            "experience_level": self.experience_level,
            "BMI": self.BMI,
            "dream_weight": self.dream_weight,
            "exercise": self.exercise,
            "weather_conditions": self.weather_conditions,
            "exercise_intensity": self.exercise_intensity,
            "created_at": self.created_at,
            "updated_at": self.updated_at
        }

        # 可以添加联合唯一约束，确保同一天只能有一条记录

    __table_args__ = (
        db.UniqueConstraint('user_id', 'created_at', name='unique_workout_record_per_day'),
    )

    # 更新运动记录的 MET 值和卡路里计算
    def calculate_calories(self):
        if self.met and self.weight and self.duration_hours:
            # 基于 MET 值和体重计算卡路里消耗，MET公式：卡路里 = MET × 体重（kg） × 时间（小时）
            self.calories_burn = self.met.met_value * self.weight * self.duration_hours
            # 通过 db.relationship，可以在 WorkoutRecord 中访问与之关联的 Met 表中的数据
            # （例如，met.met_value 即为当前记录的 MET 值）。
            db.session.commit()

    def update_workout_record(self, data):
        """根据运动记录数据更新信息"""
        try:
            # 查找对应的 MET 记录
            met_record = Mets.query.filter_by(workout_type=self.workout_type, intensity=self.exercise_intensity).first()

            if met_record:
                self.met = met_record
                self.calculate_calories()
                db.session.commit()
            else:
                raise ValueError(
                    f"No MET record found for workout_type '{self.workout_type}' and intensity '{self.exercise_intensity}'")

        except Exception as e:
            db.session.rollback()
            print(f"Error updating workout record: {e}")